<?php

namespace app\api\controller;

use app\api\validate\UserValidate;
use app\common\model\AccountLog;
use app\common\model\Change;
use app\common\model\Config;
use app\common\model\FosterOrder;
use app\common\model\Given;
use app\common\model\Goods;
use app\common\model\JlLog;
use app\common\model\JlLqLog;
use app\common\model\Recharge;
use app\common\model\ThirdUser;
use app\common\model\Users;
use app\common\model\UserSign;
use app\common\model\UserWallet;
use app\common\model\UserWalletDeal;
use app\common\model\UserWalletGiven;
use app\common\model\UserWalletLog;
use app\common\model\Wallet;
use app\common\model\Withdrawals;
use app\common\service\PlatFormFactory;
use app\common\util\MyException;
use hg\apidoc\annotation as Apidoc;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Filesystem;
use think\Image;


/**
 * @Apidoc\Title("用户")
 */
class UserApi extends Base
{
    /**
     * @Apidoc\Title("获取用户信息")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/UserInfo")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Returned("user", type="array",default="{}",desc="用户信息")
     */
    public function get_user_info()
    {
        $user = Users::where('user_id', $this->user_id)
            ->field("user_id,head_pic,nickname,realname,zhifubao,bank_name,bank_card,mobile,level,user_money,jifen,mcbt,reserve_money,is_fodder,paypwd,wechat_name,wechat_account")
            ->find();
        if ($user['realname'] && $user['bank_name'] && $user['bank_card']) {
            $user['is_ws'] = 1;
        } else {
            $user['is_ws'] = 0;
        }
        //判断是否设置了交易密码
        $is_set_paypwd = 0;
        if ($user['paypwd']) {
            $is_set_paypwd = 1;
        }
        unset($user['paypwd']);
        $user['is_set_paypwd'] = $is_set_paypwd;
        //统计认养相关
        $foster_order_model = new FosterOrder();
        //认养总数
        $ry_number = $foster_order_model->where("order_status>0 and user_id={$this->user_id}")->count();
        //已领取数量
        $ylq_number = $foster_order_model->where("order_status>0 and user_id={$this->user_id}")->sum('yet_sy');
        //待领取数量 待领取改成 对应的两
        //        $dlq_number=$foster_order_model->where("order_status=1 and user_id={$this->user_id}")->sum('surplus_yield');
        $dlq_number = $foster_order_model->where("order_status=1 and user_id={$this->user_id}")->sum(Db::Raw('(yield*10-yet_sy)'));
        //加速领取数
        $speed_number = $foster_order_model->where("order_status=1 and user_id={$this->user_id}")->sum('speed');
        /********************{签到相关}********************/
        $sign_type1 = UserSign::where("user_id=$this->user_id and type=1")->whereDay('add_time')->find();//是否已签到
        $sign_type2 = UserSign::where("user_id=$this->user_id and type=2")->whereDay('add_time')->find();//是否已看广告
        $sign_type3 = UserSign::where("user_id=$this->user_id and type=3")->whereDay('add_time')->find();//是否完成分享朋友圈
        $sign_type4 = UserSign::where("user_id=$this->user_id and type=4")->whereDay('add_time')->find();//是否完成分享微信群
        $user['level_name'] = $user['dengji']['name'];
        $user['sub_mobile'] = substr_replace($user['mobile'], '****', 3, 4);
        $user['ry_number'] = $ry_number;
        $user['ylq_number'] = $ylq_number;
        $user['dlq_number'] = $dlq_number;
        $user['speed_number'] = $speed_number;
        $user['sign_type1'] = $sign_type1 ? 1 : 0;
        $user['sign_type2'] = $sign_type2 ? 1 : 0;
        $user['sign_type3'] = $sign_type3 ? 1 : 0;
        $user['sign_type4'] = $sign_type4 ? 1 : 0;
        //统计待发放 待领取 已领取 分红总额
        $jl_log_model = new JlLog();
        $user['td_fh_dff'] = $jl_log_model->where("user_id=$this->user_id and status=-1")->sum("money");
        $user['td_fh_dlq'] = $jl_log_model->where("user_id=$this->user_id and status=1")->sum("money");
        $user['td_fh_ylq'] = $jl_log_model->where("user_id=$this->user_id and status=2")->sum("money");
        $user['td_fh_zong'] = $jl_log_model->where("user_id=$this->user_id")->sum("money");
        //加权分红总额
        $user['jq_fh_zong'] = JlLqLog::where("user_id=$this->user_id and type=2")->sum("money");
        //判断是否绑定了微信
        $third_find = ThirdUser::where("uid=$this->user_id and type=2")->find();
        if ($third_find) {
            $user['is_bind_wx'] = 1;
            $user['wx_nickname'] = $third_find['nick_name'];
        } else {
            $user['is_bind_wx'] = 0;
            $user['wx_nickname'] = '';
        }
        unset($user['dengji']);
        throw new MyException('获取成功', 200, ['user' => $user]);
    }

    /**
     * @Apidoc\Title("生成推广二维码")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/Qrcode")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Returned("user", type="array",default="{}",desc="用户信息")
     */
    public function get_user_rcode()
    {
        $user = Db::name('users')
            ->where('user_id', $this->user_id)
            ->field("user_id,head_pic,nickname,realname,mobile")
            ->find();
        $user['head_pic'] = SITE_URL . $user['head_pic'];
        $user['sub_mobile'] = substr_replace($user['mobile'], '****', 3, 4);
        require_once root_path('vendor') . "phpqrcode/phpqrcode.php";
        $userinfo = Db::name("users")->where('user_id', $this->user_id)->find();
        //这里要用前台推广网址
        //        $url=url('user/reg',['rekey'=>$userinfo['mobile']])->domain(SITE_URL)->build();
        // $url = SITE_URL . '/h5/pages/auth/register?uniacid='. config('site.uniacid') .'&rekey=' . $userinfo['user_id'];
        $url = cdnurl('/h5/pages/auth/register?uniacid='. config('site.uniacid') .'&rekey=' . $userinfo['user_id'], true);
        $img_name = md5('zhang' . $this->user_id . 'zhang');
        \QRcode::png($url, 'assets/qrcode/' . $img_name . '.png', 1, 10, 2);
        $img = "assets/qrcode/{$img_name}.png";
        $base_name = 'assets/qrcode/tgzm.png';
        $base_img = imagecreatefrompng($base_name);
        //背景图宽高
        $base_img_w = imagesx($base_img);
        $base_img_h = imagesy($base_img);
        //二维码宽高
        $img_path = imagecreatefrompng($img);
        $width = imagesx($img_path);
        $height = imagesy($img_path);

        $font = 'resource/font/msyh.ttf';
        $black = imagecolorallocate($base_img, 0, 0, 0);
        //获取姓名&宽高
        $realname = $userinfo['realname'];
        $realname_wh = $this->get_font_wh(30, 0, $font, $realname);
        //获取标题&宽高
        $str = "邀请您成为农场主";
        $str_wh = $this->get_font_wh(40, 0, $font, $str);
        //获取电话&宽高
        $mobile = '电话:' . $userinfo['mobile'];
        $mobile_wh = $this->get_font_wh(30, 0, $font, $mobile);
        //获取ID&宽高
        $user_id = 'ID:' . $userinfo['user_id'];
        $user_id_wh = $this->get_font_wh(30, 0, $font, $user_id);
        //输出一个灰色的字符串作为阴影
        imagettftext($base_img, 30, 0, ($base_img_w - $realname_wh['width']) / 2, 420, $black, $font, $realname);
        imagettftext($base_img, 40, 0, ($base_img_w - $str_wh['width']) / 2, 520, $black, $font, $str);
        imagettftext($base_img, 30, 0, ($base_img_w - $mobile_wh['width']) / 2, 610, $black, $font, $mobile);
        imagettftext($base_img, 30, 0, ($base_img_w - $user_id_wh['width']) / 2, 700, $black, $font, $user_id);
        //画入二维码
        imagecopyresampled($base_img, $img_path, ceil(($base_img_w - 300) / 2), 780, 0, 0, 300, 300, $width, $height);
        imagepng($base_img, "assets/qrcode/tg_{$img_name}.png");
        imagedestroy($base_img);
        $img_url = "/assets/qrcode/{$img_name}.png";
        $result['user'] = $user;
        $result['img'] = cdnurl($img_url, true);
        // $result['share_img'] = SITE_URL . "/assets/qrcode/tg_{$img_name}.png";
        $result['share_img'] = cdnurl("/assets/qrcode/tg_{$img_name}.png", true);

        $distributionConfig = Config::where('name', 'distribution')->findOrEmpty();

        if ($distributionConfig) {
            $result['distribution_config'] = json_decode($distributionConfig->value, true);
        }


        throw new MyException('获取成功', 200, $result);
    }

    public function get_user_rcode1()
    {
        $uinfo['head_pic'] = $this->user['head_pic'];
        $uinfo['nickname'] = $this->user['nickname'];
        $uinfo['sub_mobile'] = substr_replace($this->user['mobile'], '****', 3, 4);
        $data['user'] = $uinfo;
        $wxpay = new WxPayXcx($this->app);
        $qrcode = $wxpay->getWxQRCode($this->user_id);
        $data['img'] = SITE_URL . $qrcode;
        throw new MyException("获取成功", 200, $data);
    }

    /**
     * 获取字体宽高
     * @param float $font_size 字体大小
     * @param float $angle 旋转角度
     * @param string $ttf 字体文件
     * @param string $str 字符串
     */
    private function get_font_wh($font_size, $angle, $ttf, $str)
    {
        /*解释
        imagettfbbox() 返回一个含有 8 个单元的数组表示了文本外框的四个角：
        0 左下角 X 位置
        1 左下角 Y 位置
        2 右下角 X 位置
        3 右下角 Y 位置
        4 右上角 X 位置
        5 右上角 Y 位置
        6 左上角 X 位置
        7 左上角 Y 位置
        */
        $f = imagettfbbox($font_size, $angle, $ttf, $str);
        //获取字符串宽度  右下角 X 位置 - 左下角 X 位置
        $width = $f[2] - $f[0];
        //获取字符串高度  左下角 Y 位置 - 左上角 Y 位置
        $height = $f[1] - $f[7];
        return ['width' => $width, 'height' => $height];
    }

    /**
     * @Apidoc\Title("团队列表")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_td_list")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("ceng",type="int",require=true,default="",desc="层级0一层1二层")
     */
    public function team_list()
    {
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        $ceng = input('ceng');
        $where = [];
        if ($ceng) {
            $where[] = ['jt_id', '=', $this->user_id];
        } else {
            $where[] = ['reid', '=', $this->user_id];
        }
        $list = Users::where($where)
            ->order('reg_time desc,user_id desc')
            ->page($pi, $ps)
            ->field("user_id,nickname,level,mobile,head_pic,(td_yeji) as td_yeji")
            ->select()
            ->each(function ($item) {
                $item['level_name'] = $item['dengji']['name'];
                $item['sub_mobile'] = substr_replace($item['mobile'], '****', 3, 4);
                $item['ry_num'] = $item['ry_num'];
                $item['ry_money'] = $item['ry_money'];
                unset($item['dengji'], $item['mobile']);
                return $item;
            });
        //获取业绩相关
        $result['td_all_num'] = $this->user['td_all_num'];
        $result['td_ry_yeji'] = $this->user['td_ry_yeji'];
        $result['day_ry_yeji'] = $this->user['day_ry_yeji'];
        $result['month_ry_yeji'] = $this->user['month_ry_yeji'];
        $result['day_td_ry_yeji'] = $this->user['day_td_ry_yeji'];
        $result['td_month_yeji'] = $this->user['td_month_yeji'];
        $result['daqu_yeji'] = get_dq_td_yeji($this->user_id);
        $result['xiaoqu_yeji'] = get_xq_td_yeji($this->user_id);
        $data['list'] = $list;
        $data['result'] = $result;
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("会员签到")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/user_qd")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("type",type="int",require=true,default="",desc="类型1签到2看广告3分享朋友圈4分享微信")
     */
    public function user_sign()
    {
        $type = input('type');
        if (!in_array($type, [1, 2, 3, 4])) {
            throw new MyException('提交参数有误');
        }
        $find_where['user_id'] = $this->user_id;
        $find_where['type'] = $type;
        $find = UserSign::where($find_where)->whereDay('add_time')->find();
        if ($find) {
            throw new MyException('已经签到了哦~');
        } else {
            $money = 0;
            //用户更新为已签到
            if ($this->user['is_fodder'] == 0) {
                $user_update['is_fodder'] = 1;
                $this->user->save($user_update);
            }
            $insert['user_id'] = $this->user_id;
            $insert['type'] = $type;
            $insert['money'] = $money;
            $res = UserSign::create($insert);
        }
        if ($res) {
            throw new MyException('操作成功', 200);
        } else {
            throw new MyException('操作失败');
        }
    }

    /**
     * @Apidoc\Title("收藏列表")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/CollectList")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Returned("collect", type="array",default="{}",desc="收藏列表数据")
     */
    public function collect_list()
    {
        $user_id = $this->user_id;
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        $model = new Goods();
        $lists = Db::name('goods_collect')
            ->alias('gc')
            ->join('goods g', 'gc.goods_id=g.goods_id', 'left')
            ->where('gc.user_id=' . $user_id)
            ->field('gc.collect_id,gc.goods_id,g.goods_img,g.goods_name')
            ->page($pi, $ps)
            ->select()->each(function ($item) use ($model) {
                $item['goods_img'] = SITE_URL . $item['goods_img'];
                $goods = $model->find($item['goods_id']);
                $item['goods_price'] = $goods['price'];
                return $item;
            });
        $data['collect'] = $lists;
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("添加/取消收藏")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/EditCollect")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Param("goods_id",type="int",require=true,default="1",desc="商品id")
     * @Apidoc\Param("type",type="int",require=true,default="1",desc="操作类型")
     */
    public function edit_collect()
    {
        $user_id = $this->user_id;
        if ($user_id == 0) {
            return json(['code' => 400, 'msg' => '请先登录']);
        }
        $type = input('type');//1收藏2取消
        $goods_id = input('goods_id');
        $map['user_id'] = $user_id;
        $map['goods_id'] = $goods_id;
        $map['add_time'] = time();
        $collect = Db::name('goods_collect')->where('goods_id=' . $goods_id . ' and user_id=' . $user_id)->find();
        if ($collect) {
            if ($type == 1) {
                $code = 400;
                $msg = '您已收藏此商品';
            } else {
                $msg = '取消收藏成功';
                $code = 200;
                Db::name('goods_collect')->where('goods_id=' . $goods_id . ' and user_id=' . $user_id)->delete();
            }
        } else {
            if ($type == 1) {
                $msg = '收藏成功';
                $code = 200;
                Db::name('goods_collect')->insert($map);
            } else {
                $code = 400;
                $msg = '您尚未收藏此商品';
            }
        }
        throw new MyException($msg, $code);
    }

    /**
     * @Apidoc\Title("我的足迹")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/VisitList")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Returned("collect", type="array",default="{}",desc="足迹列表数据")
     */
    function visit_list()
    {
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        $model = new Goods();
        $list = [];
        //先删除下架的商品
        $user_visit = Db::name('goods_visit')->where("user_id=$this->user_id")->field('goods_id,visit_id')->select();
        foreach ($user_visit as $value) {
            $good = Db::name('goods')->where('goods_id', $value['goods_id'])->field('is_on_sale')->find();
            if ($good['is_on_sale'] != 1) {
                Db::name('goods_visit')->where("visit_id={$value['visit_id']}")->delete();
            }
        }
        $lists = Db::name('goods_visit')
            ->alias('gv')
            ->join('goods g', 'g.goods_id=gv.goods_id', 'left')
            ->where('gv.user_id=' . $this->user_id)
            ->field('gv.visittime,gv.goods_id,gv.visit_id,g.goods_img,g.goods_name')
            ->page($pi, $ps)
            ->order('gv.visittime desc,gv.visit_id desc')
            ->select()->each(function ($item) use ($model) {
                $item['goods_img'] = SITE_URL . $item['goods_img'];
                $goods = $model->find($item['goods_id']);
                $item['goods_price'] = $goods['price'];
                return $item;
            })->toArray();
        foreach ($lists as $val) {
            $date = date('Y年m月d日', $val['visittime']);
            $val['selected'] = 0;
            unset($val['visittime']);
            $list[$date][] = $val;
        }
        $arr = array();
        foreach ($list as $key => $val) {
            $brr['title'] = $key;
            $brr['child'] = $val;
            $arr[] = $brr;
        }
        $data['list'] = $arr;
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("删除足迹")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/DelVisit")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Param("visit_id",type="array",require=true,default="1,2",desc="足迹id")
     */
    function del_visit()
    {
        $ids = input('ids');
        if (empty($ids)) {
            throw new MyException('请选择数据');
        }
        $res = Db::name("goods_visit")->whereIn('visit_id', $ids)->delete();
        if ($res) {
            throw new MyException('删除成功', 200);
        } else {
            throw new MyException('删除失败');
        }
    }

    /**
     * @Apidoc\Title("地址列表")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/AddressList")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Returned("address", type="array",default="{}",desc="地址列表数据")
     */
    function address_list()
    {
        $address_lists = Db::name('user_address')->order('is_default desc')->where('user_id', $this->user_id)->select();
        $data['address'] = $address_lists;
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("获取要修改地址的信息")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/Address")
     * @Apidoc\Param("address_id",type="int",require=true,default="0",desc="地址id")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Returned("address", type="array",default="{}",desc="地址数据")
     */
    function address()
    {
        $address_id = input('post.address_id/d', 0);
        if ($address_id) {
            $where['address_id'] = $address_id;
            $where['user_id'] = $this->user_id;
            $address_lists = Db::name('user_address')
                ->where($where)
                ->find();
            if (empty($address_lists)) {
                throw new MyException('地址信息有误', 100);
            }
            $data['address'] = $address_lists;
        }
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("保存地址")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/SaveAddress")
     * @Apidoc\Param("address_id",type="int",default="0",desc="地址id")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Param("consignee",type="string",require=true,default="张三",desc="收货人姓名")
     * @Apidoc\Param("mobile",type="string",require=true,default="17854568191",desc="收货人电话")
     * @Apidoc\Param("pid",type="int",require=true,default="",desc="省份id")
     * @Apidoc\Param("cid",type="int",require=true,default="",desc="城市id")
     * @Apidoc\Param("did",type="int",require=true,default="",desc="区/县id")
     * @Apidoc\Param("province",type="string",require=true,default="",desc="省份")
     * @Apidoc\Param("city",type="string",require=true,default="",desc="城市")
     * @Apidoc\Param("district",type="string",require=true,default="",desc="区/县")
     * @Apidoc\Param("address",type="string",require=true,default="交通未来城",desc="收货人详细地址")
     * @Apidoc\Param("is_default",type="int",require=true,default="0",desc="是否设为默认地址")
     */
    public function save_address()
    {
        $address_id = input('address_id/d', 0);
        $data = input('post.');
        if (empty($data['consignee'])) {
            throw new MyException('请填写收货人');
        }
        if (empty($data['mobile']) || !check_mobile($data['mobile'])) {
            throw new MyException('手机号码格式有误');
        }
        if (empty($data['province'])) {
            throw new MyException('请选择省份');
        }
        if (empty($data['city'])) {
            throw new MyException('请选择城市');
        }
        if (empty($data['district'])) {
            throw new MyException('请选择地区');
        }
        if (empty($data['address'])) {
            throw new MyException('请填写详细地址');
        }
        //如果为默认地址，则所有地址设为非默认
        if ($data['is_default'] == 1) {
            Db::name('user_address')->where('user_id', $this->user_id)->update(['is_default' => 0]);
        }
        if ($address_id) {
            $where['address_id'] = $address_id;
            $where['user_id'] = $this->user_id;
            //如果当前地址是默认 并且更改为非默认地址
            $is_default = Db::name('user_address')->where('address_id', $address_id)->value('is_default');
            if ($is_default == 1 && $data['is_default'] == 0) {
                $count = Db::name('user_address')->where('user_id', $this->user_id)->count();
                $is_default_where[] = ['user_id', '=', $this->user_id];
                if ($count > 1) {
                    $is_default_where[] = ['address_id', '<>', $address_id];
                    Db::name('user_address')->where($is_default_where)->limit(1)->update(['is_default' => 1]);
                } else {
                    $data['is_default'] = 1;
                }
            }
            unset($data['address_id']);
            unset($data['sign']);
            Db::name('user_address')->where($where)->update($data);
        } else {
            $count = Db::name('user_address')->where('user_id=' . $this->user_id)->count();
            if ($count >= 10) {
                throw new MyException('最多可添加10条地址');
            }
            if ($count == 0) {
                $data['is_default'] = 1;
            }
            unset($data['address_id']);
            unset($data['sign']);
            Db::name('user_address')->insert($data);
        }
        throw new MyException('操作成功', 200);
    }

    /**
     * @Apidoc\Title("删除地址")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/DelAddress")
     * @Apidoc\Header(ref="auth")
     * @Apidoc\Param("address_id",type="int",require=true,default="0",desc="地址id")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     */
    public function del_address()
    {
        $id = input('address_id/d');
        $address = Db::name('user_address')->where("address_id", $id)->find();
        $row = Db::name('user_address')->where(array('user_id' => $this->user_id, 'address_id' => $id))->delete();
        // 如果删除的是默认收货地址 则要把第一个地址设置为默认收货地址
        if ($address['is_default'] == 1) {
            $address2 = Db::name('user_address')->where("user_id", $this->user_id)->find();
            //当查询结果有的时候，再进行下一步操作
            $address2 && Db::name('user_address')->where("address_id", $address2['address_id'])->save(array('is_default' => 1));
        }
        if ($row != false) {
            throw new MyException('删除成功', 200);
        } else {
            throw new MyException('删除失败');
        }
    }

    /**
     * @Apidoc\Title("修改昵称")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/edit_nc")
     * @Apidoc\Param("step",type="int",require=true,default="1",desc="当前步数")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("nickname",type="string",default="",desc="用户昵称")
     */
    public function edit_nickname()
    {
        $step = input('step');
        if (empty($step) || !in_array($step, [1, 2])) {
            throw new MyException('提交参数有误');
        }
        if ($step == 1) {
            $return_data['nickname'] = $this->user['nickname'];
            throw new MyException('获取成功', 10, $return_data);
        } else {
            $nickname = input('nickname');
            if (empty($nickname)) {
                return json(['code' => 400, 'msg' => '昵称不能为空']);
            }
            $user_update['nickname'] = $nickname;
            $res = $this->user->save($user_update);
            if ($res) {
                throw new MyException('修改成功', 200);
            } else {
                throw new MyException('没有任何修改');
            }
        }
    }

    /**
     * @Apidoc\Title("修改个人信息")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/EditUserInfo")
     * @Apidoc\Param("step",type="int",require=true,default="1",desc="当前步数")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Param("realname",type="string",require=true,default="",desc="真实姓名")
     * @Apidoc\Param("bank_name",type="string",require=true,default="",desc="开户银行")
     * @Apidoc\Param("bank_card",type="string",require=true,default="",desc="银行卡号")
     * @Apidoc\Param("code",type="int",default="",desc="验证码")
     */
    public function set_user_info()
    {
        $step = input('step');
        if (empty($step) || !in_array($step, [1, 2])) {
            throw new MyException('提交参数有误');
        }
        $user_info_sms_enable = getSysConfig('sms.user_info_sms_enable');
        $sms_time_out = getSysConfig('sms.sms_time_out');//过期时间
        if ($step == 1) {
            $return_data['user_info_sms_enable'] = $user_info_sms_enable;
            $return_data['sms_time_out'] = $sms_time_out;
            $return_data['mobile'] = $this->user['mobile'];
            $return_data['realname'] = $this->user['realname'];
            $return_data['bank_name'] = $this->user['bank_name'];
            $return_data['bank_card'] = $this->user['bank_card'];
            throw new MyException('获取成功', 10, $return_data);
        } else {
            $data = input('post.');
            $data['mobile'] = $this->user['mobile'];
            try {
                validate(UserValidate::class)->scene('info')->check($data);
            } catch (ValidateException $e) {
                $error = $e->getError();
                throw new MyException($error);
            }
            $update['realname'] = $data['realname'];
            $update['bank_name'] = $data['bank_name'];
            $update['bank_card'] = $data['bank_card'];
            Db::name('users')->where('user_id', $this->user_id)->update($update);
            throw new MyException('修改成功', 200);
        }
    }

    /**
     * @Apidoc\Title("修改登录密码")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/set_password")
     * @Apidoc\Param("step",type="int",require=true,default="",desc="当前步数")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("password",type="string",require=true,default="",desc="新密码")
     * @Apidoc\Param("oldpassword",type="string",require=true,default="",desc="原密码")
     * @Apidoc\Param("conpassword",type="string",require=true,default="",desc="确认新密码")
     * @Apidoc\Param("code",type="int",default="",desc="验证码")
     */
    public function password()
    {
        $step = input('step');
        if (empty($step) || !in_array($step, [1, 2])) {
            throw new MyException('提交参数有误');
        }
        $edit_pwd_sms_enable = getSysConfig('sms.edit_pwd_sms_enable');
        $sms_time_out = getSysConfig('sms.sms_time_out');//过期时间
        if ($step == 1) {
            $return_data['edit_pwd_sms_enable'] = $edit_pwd_sms_enable;
            $return_data['sms_time_out'] = $sms_time_out;
            $return_data['mobile'] = $this->user['mobile'];
            throw new MyException('获取成功', 10, $return_data);
        } else {
            $data = input('post.');
            $data['sms'] = $edit_pwd_sms_enable;
            $data['mobile'] = $this->user['mobile'];
            try {
                validate(UserValidate::class)->scene('pass')->check($data);
            } catch (ValidateException $e) {
                $error = $e->getError();
                throw new MyException($error);
            }
            $map['password'] = encrypt($data['password']);
            Db::name('users')->where('user_id', $this->user_id)->update($map);
            throw new MyException('修改成功', 200);
        }
    }

    /**
     * @Apidoc\Title("修改交易密码")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/set_paypwd")
     * @Apidoc\Param("step",type="int",require=true,default="",desc="当前步数")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("password",type="string",require=true,default="",desc="新密码")
     * @Apidoc\Param("oldpassword",type="string",require=true,default="",desc="原密码")
     * @Apidoc\Param("conpassword",type="string",require=true,default="",desc="确认新密码")
     * @Apidoc\Param("code",type="int",default="",desc="验证码")
     */
    public function paypwd()
    {
        $step = input('step');
        if (empty($step) || !in_array($step, [1, 2])) {
            throw new MyException('提交参数有误');
        }
        //判断是否设置了交易密码
        $is_set_paypwd = 0;
        if ($this->user['paypwd']) {
            $is_set_paypwd = 1;
        }
        $edit_paypwd_sms_enable = getSysConfig('sms.edit_paypwd_sms_enable');
        $sms_time_out = getSysConfig('sms.sms_time_out');//过期时间
        if ($step == 1) {
            $return_data['edit_paypwd_sms_enable'] = $edit_paypwd_sms_enable;
            $return_data['sms_time_out'] = $sms_time_out;
            $return_data['is_set_paypwd'] = $is_set_paypwd;
            $return_data['mobile'] = $this->user['mobile'];
            throw new MyException('获取成功', 10, $return_data);
        } else {
            $data = input('post.');
            if ($is_set_paypwd == 1) {
                $data['sms'] = $edit_paypwd_sms_enable;
            }
            $data['is_set_paypwd'] = $is_set_paypwd;
            $data['mobile'] = $this->user['mobile'];
            if ($is_set_paypwd == 1) {
                $scene = 'paypwd';
            } else {
                $scene = 'noPaypwd';
            }
            try {
                validate(UserValidate::class)->scene($scene)->check($data);
            } catch (ValidateException $e) {
                $error = $e->getError();
                throw new MyException($error);
            }
            $map['paypwd'] = encrypt($data['password']);
            $this->user->save($map);
            throw new MyException('修改成功', 200);
        }
    }

    /**
     * @Apidoc\Title("绑定微信")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/set_wechat")
     * @Apidoc\Param("step",type="int",require=true,default="",desc="当前步数")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("zhifubao",type="string",require=true,default="",desc="支付宝账号")
     * @Apidoc\Param("realname",type="string",require=true,default="",desc="支付宝姓名")
     */
    public function bind_wechat()
    {
        $step = input('step');
        if (empty($step) || !in_array($step, [1, 2])) {
            throw new MyException('提交参数有误');
        }
        if ($step == 1) {
            $return_data['mobile'] = $this->user['mobile'];
            $return_data['wechat_name'] = $this->user['wechat_name'];
            $return_data['wechat_account'] = $this->user['wechat_account'];
            throw new MyException('获取成功', 10, $return_data);
        } else {
            $data = input('post.');
            try {
                validate(UserValidate::class)->scene('wechat')->check($data);
            } catch (ValidateException $e) {
                $error = $e->getError();
                throw new MyException($error);
            }
            $map['wechat_account'] = $data['wechat_account'];
            $map['wechat_name'] = $data['wechat_name'];
            $this->user->save($map);
            throw new MyException('修改成功', 200);
        }
    }

    /**
     * @Apidoc\Title("绑定支付宝")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/set_zfb")
     * @Apidoc\Param("step",type="int",require=true,default="",desc="当前步数")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("zhifubao",type="string",require=true,default="",desc="支付宝账号")
     * @Apidoc\Param("realname",type="string",require=true,default="",desc="支付宝姓名")
     */
    public function bind_zfb()
    {
        $step = input('step');
        if (empty($step) || !in_array($step, [1, 2])) {
            throw new MyException('提交参数有误');
        }
        if ($step == 1) {
            $return_data['mobile'] = $this->user['mobile'];
            $return_data['zhifubao'] = $this->user['zhifubao'];
            $return_data['realname'] = $this->user['realname'];
            throw new MyException('获取成功', 10, $return_data);
        } else {
            $data = input('post.');
            try {
                validate(UserValidate::class)->scene('zfb')->check($data);
            } catch (ValidateException $e) {
                $error = $e->getError();
                throw new MyException($error);
            }
            $map['zhifubao'] = $data['zhifubao'];
            $map['realname'] = $data['realname'];
            $this->user->save($map);
            throw new MyException('修改成功', 200);
        }
    }

    /**
     * @Apidoc\Title("绑定支付宝、微信")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/bind_zfb_wx")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Param("openId",type="string",require=true,default="",desc="openId")
     * @Apidoc\Param("nickName",type="string",require=true,default="",desc="微信昵称")
     * @Apidoc\Param("gender",type="int",require=true,default="",desc="性别")
     * @Apidoc\Param("city",type="int",require=true,default="",desc="城市")
     * @Apidoc\Param("province",type="int",require=true,default="",desc="省份")
     * @Apidoc\Param("avatarUrl",type="int",require=true,default="",desc="微信头像")
     * @Apidoc\Param("unionId",type="int",require=true,default="",desc="unionId")
     */
    public function bind_third()
    {
        $openId = input('openId');
        $unionId = input('unionId');
        $nickName = input('nickName');
        $gender = input('gender');
        $city = input('city');
        $province = input('province');
        $avatarUrl = input('avatarUrl');
        if (empty($openId) && empty($unionId)) {
            throw new MyException('提交参数有误');
        }
        $third_model = new ThirdUser();
        if ($unionId) {
            $third_find_where['unionid'] = $unionId;
        } else {
            $third_find_where['openid'] = $openId;
        }
        $third_find = $third_model->where($third_find_where)->find();
        if ($third_find) {
            $user = Users::find($third_find['uid']);
            if ($user) {
                $third_update['uid'] = $this->user_id;
                $third_update['openid'] = $openId;
                $third_update['unionid'] = $unionId;
                $log = $third_find->save($third_update);
            } else {
                throw new MyException('该微信已绑定其它账户');
            }
        } else {
            //插入到第三方用户信息表
            $insert['uid'] = $this->user_id;
            $insert['type'] = 2;
            $insert['avatar'] = $avatarUrl;
            $insert['province'] = $province;
            $insert['city'] = $city;
            $insert['nick_name'] = $nickName;
            $insert['gender'] = $gender;
            $insert['openid'] = $openId;
            $insert['unionid'] = $unionId;
            $log = $third_model->save($insert);
        }
        if ($log) {
            throw new MyException('绑定成功', 200);
        } else {
            throw new MyException('绑定失败');
        }
    }

    /**
     * @Apidoc\Title("上传头像")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/UploadPic")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Param("file",type="file",require=true,desc="上传的头像文件")
     */
    public function upload_pic()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        $path = input('path', 'upload');
        // 移动到框架应用根目录/uploads/ 目录下
        if ($file) {
            $info = Filesystem::putFile($path, $file);
            if ($info) {
                $img = UPLOAD_PATH . $info;
                $this->saveImage($img);
                if ($path == 'head_pic') {
                    Db::name('users')->where('user_id', $this->user_id)->update(['head_pic' => $img]);
                }
                // throw new MyException('修改成功', 200, ['img' => SITE_URL . $img]);
                throw new MyException('修改成功', 200, ['img' => cdnurl($img, true)]);
            } else {
                // 上传失败获取错误信息
                throw new MyException('文件上传失败');
            }
        }
        throw new MyException('上传文件有误');
    }

    private function saveImage($path)
    {
        $image = Image::open('.' . $path);
        $image->thumb(600, 600, true)->save('.' . $path);
    }

    /**
     * @Apidoc\Title("资金转赠")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/user_given")
     * @Apidoc\Param("step",type="int",require=true,default="",desc="当前步数")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("dfmobile",type="string",require=true,default="",desc="对方手机号码")
     * @Apidoc\Param("money",type="string",require=true,default="",desc="转赠金额")
     * @Apidoc\Param("code",type="int",default="",desc="验证码")
     */
    public function given()
    {
        $step = input('step');
        if (empty($step) || !in_array($step, [1, 2])) {
            throw new MyException('提交参数有误');
        }
        $user_given_sms_enable = getSysConfig('sms.user_given_sms_enable');
        $sms_time_out = getSysConfig('sms.sms_time_out');//过期时间
        $given_config = getSysConfig('given');
        //粮票转赠开关
        $lp_given_open = getSysConfig('given.lp_given_open');
        //牧场补贴转赠开关
        $given_open = getSysConfig('given.given_open');
        //判断是否完善了交易密码
        if (empty($this->user['paypwd'])) {
            throw new MyException('请先设置交易密码', 50);
        }
        if ($step == 1) {
            $return_data['user_given_sms_enable'] = $user_given_sms_enable;
            $return_data['sms_time_out'] = $sms_time_out;
            $return_data['mobile'] = $this->user['mobile'];
            $return_data['user_money'] = $this->user['user_money'];
            $return_data['mcbt'] = $this->user['mcbt'];
            $return_data['given_config'] = $given_config;
            throw new MyException('获取成功', 10, $return_data);
        } else {
            $type = input('type');
            if (!in_array($type, [1, 3])) {
                throw new MyException('提交参数有误');
            }
            if ($type == 1) {
                if ($lp_given_open == 0) {
                    throw new MyException('粮票转赠暂未开放');
                }
            } else {
                if ($given_open == 0) {
                    throw new MyException('牧场补贴转赠暂未开放');
                }
            }
            $dfmobile = input('dfmobile');
            $uid = input('uid/d');
            $money = input('money');
            $code = input('code');
            if ($money == '' || !is_numeric($money) || $money <= 0) {
                throw new MyException('请输入正确的转赠金额');
            }
            if (empty($dfmobile)) {
                throw new MyException('请输入对方手机号码');
            }
            if (empty($uid)) {
                throw new MyException('请输入对方ID');
            }
            $df_where['mobile'] = $dfmobile;
            $df_where['user_id'] = $uid;
            $dfuser = Users::where($df_where)->find();
            if (empty($dfuser)) {
                throw new MyException('会员不存在');
            }
            if ($dfmobile == $this->user['mobile']) {
                throw new MyException('转赠人不能为自己');
            }
            if ($type == 1) {
                //转赠手续费
                $given_sxf = $given_config['lp_given_sxf'];
                //最低转赠金额
                $given_min = $given_config['lp_given_min'];
                //转赠金额系数
                $given_xishu = $given_config['lp_given_xishu'];
                //单日最大转赠额度
                $given_daymax = $given_config['lp_given_daymax'];
                if ($given_min > 0) {
                    if ($money < $given_min) {
                        $msg = sprintf('粮票最少转赠数量为%s元!', $given_min);
                        throw new MyException($msg);
                    }
                }
                if ($given_xishu > 0) {
                    if (($money * 100000) % ($given_xishu * 100000) != 0) {
                        $msg = sprintf('粮票转赠数量为%s元的整数倍!', $given_xishu);
                        throw new MyException($msg);
                    }
                }
                if ($given_daymax > 0) {
                    $where[] = ['user_id', '=', $this->user_id];
                    $where[] = ['type', '=', 1];
                    $sum = Db::name('given')->where($where)->whereDay('add_time')->sum('money');
                    if (($sum + $money) > $given_daymax) {
                        throw new MyException('当日粮票转赠额度超出限制');
                    }
                }
                $user_money = Users::where('user_id', $this->user_id)->value('user_money');
                if ($money > $user_money) {
                    $msg = sprintf('粮票不足,可用%s元!', $user_money);
                    throw new MyException($msg);
                }
                $text = 'user_money';
            } else {
                //转赠手续费
                $given_sxf = $given_config['given_sxf'];
                //最低转赠金额
                $given_min = $given_config['given_min'];
                //转赠金额系数
                $given_xishu = $given_config['given_xishu'];
                //单日最大转赠额度
                $given_daymax = $given_config['given_daymax'];
                if ($given_min > 0) {
                    if ($money < $given_min) {
                        $msg = sprintf('牧场补贴最少转赠数量为%s元!', $given_min);
                        throw new MyException($msg);
                    }
                }
                if ($given_xishu > 0) {
                    if (($money * 100000) % ($given_xishu * 100000) != 0) {
                        $msg = sprintf('牧场补贴转赠数量为%s元的整数倍!', $given_xishu);
                        throw new MyException($msg);
                    }
                }
                if ($given_daymax > 0) {
                    $where[] = ['user_id', '=', $this->user_id];
                    $where[] = ['type', '=', 3];
                    $sum = Db::name('given')->where($where)->whereDay('add_time')->sum('money');
                    if (($sum + $money) > $given_daymax) {
                        throw new MyException('当日牧场补贴转赠额度超出限制');
                    }
                }
                $user_money = Users::where('user_id', $this->user_id)->value('mcbt');
                if ($money > $user_money) {
                    $msg = sprintf('牧场补贴不足,可用%s元!', $user_money);
                    throw new MyException($msg);
                }
                $text = 'mcbt';
            }
            if ($user_given_sms_enable) {
                $check = yz_sms_code($this->user['mobile'], $code);
                if ($check['code'] != 200) {
                    throw new MyException($check['msg']);
                }
            }
            $taxfee = $money * ($given_sxf / 100);
            $true_money = $money - $taxfee;
            $zr_mobile = substr_replace($dfuser['mobile'], '****', 3, 4);
            $zc_mobile = substr_replace($this->user['mobile'], '****', 3, 4);
            $desc = sprintf("转让%s", $zr_mobile);
            $log = accountLog($this->user_id, -$money, $desc, $type);
            if ($log) {
                $user = Users::find($this->user_id);
                if ($user[$text] >= 0) {
                    $insert['user_id'] = $this->user_id;
                    $insert['dfuid'] = $dfuser['user_id'];
                    $insert['type'] = $type;
                    $insert['money'] = $money;
                    $insert['taxfee'] = $taxfee;
                    $insert['true_money'] = $true_money;
                    $log1 = Given::create($insert);
                    if ($log1) {
                        $desc = sprintf("%s转入", $zc_mobile);
                        $log2 = accountLog($dfuser['user_id'], $true_money, $desc, $type);
                    }
                }
            }
            if ($log && $log1 && $log2) {
                throw new MyException('转赠成功', 200);
            } else {
                throw new MyException('转赠失败');
            }
        }
    }

    /**
     * @Apidoc\Title("转赠记录")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/zz_list")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     */
    public function given_list()
    {
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        $where = "user_id={$this->user_id} or dfuid={$this->user_id}";
        $account_log = new Given();
        $lists = $account_log
            ->where($where)
            ->order('id desc')
            ->page($pi, $ps)
            ->field('user_id,dfuid,money,taxfee,true_money,add_time,type')
            ->select()->each(function ($item) {
                if ($item['user_id'] == $this->user_id) {
                    $item['zr_type'] = 1;
                } else {
                    $item['zr_type'] = 2;
                }
                $item['mobile'] = substr_replace($item['user']['mobile'], '****', 3, 4);
                $item['sub_mobile'] = substr_replace($item['dfuser']['mobile'], '****', 3, 4);
                $item['type_text'] = $item['type_text'];
                unset($item['dfuser'], $item['user']);
                return $item;
            });
        throw new MyException('获取成功', 200, ['list' => $lists]);
    }

    /**
     * @Apidoc\Title("钻石转化")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/ZhuanHua")
     * @Apidoc\Param("step",type="int",require=true,default="",desc="当前步数")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("money",type="string",require=true,default="",desc="转化金额")
     * @Apidoc\Param("code",type="int",default="",desc="验证码")
     */
    public function change()
    {
        $step = input('step');
        if (empty($step) || !in_array($step, [1, 2])) {
            throw new MyException('提交参数有误');
        }
        $user_change_sms_enable = getSysConfig('sms.user_change_sms_enable');
        $sms_time_out = getSysConfig('sms.sms_time_out');//过期时间
        //钻石转化开关
        $change_open = getSysConfig('change.change_open');
        if ($step == 1) {
            $return_data['user_change_sms_enable'] = $user_change_sms_enable;
            $return_data['sms_time_out'] = $sms_time_out;
            $return_data['mobile'] = $this->user['mobile'];
            $return_data['user_money'] = $this->user['user_money'];
            $return_data['jinbi'] = $this->user['jinbi'];
            $return_data['change_open'] = $change_open;
            throw new MyException('获取成功', 10, $return_data);
        } else {
            $money = input('money');
            $code = input('code');
            if ($money == '' || !is_numeric($money) || $money <= 0) {
                throw new MyException('请输入正确的转化金额');
            }
            //转化手续费
            $change_sxf = getSysConfig('change.change_sxf');
            //最低转化金额
            $change_min = getSysConfig('change.change_min');
            //转化金额系数
            $change_xishu = getSysConfig('change.change_xishu');
            //单日最大转化额度
            $change_daymax = getSysConfig('change.change_daymax');
            if ($change_min > 0) {
                if ($money < $change_min) {
                    $msg = sprintf('最少转化金额为%s元!', $change_min);
                    throw new MyException($msg);
                }
            }
            if ($change_xishu > 0) {
                if (($money * 10000) % ($change_xishu * 10000) != 0) {
                    $msg = sprintf('转化金额为%s元的整数倍!', $change_xishu);
                    throw new MyException($msg);
                }
            }
            if ($change_daymax > 0) {
                $where[] = ['user_id', '=', $this->user_id];
                $sum = Db::name('change')->where($where)->whereDay('add_time')->sum('money');
                if (($sum + $money) > $change_daymax) {
                    throw new MyException('当日转化额度超出限制');
                }
            }
            if ($money > $this->user['user_money']) {
                $msg = sprintf('钻石不足,可用%s元!', $this->user['user_money']);
                throw new MyException($msg);
            }
            if ($user_change_sms_enable) {
                $check = yz_sms_code($this->user['mobile'], $code);
                if ($check['code'] != 200) {
                    throw new MyException($check['msg']);
                }
            }
            $taxfee = $money * ($change_sxf / 100);
            $true_money = $money - $taxfee;
            $desc = "转化金币";
            $log = accountLog($this->user_id, -$money, $desc);
            if ($log) {
                $user = get_user_info($this->user_id);
                if ($user['user_money'] >= 0) {
                    $insert['user_id'] = $this->user_id;
                    $insert['money'] = $money;
                    $insert['taxfee'] = $taxfee;
                    $insert['true_money'] = $true_money;
                    $log1 = Change::create($insert);
                    if ($log1) {
                        $log2 = accountLog($this->user_id, $true_money, '钻石转化', 2);
                    }
                }
            }
            if ($log && $log1 && $log2) {
                throw new MyException('转化成功', 200);
            } else {
                throw new MyException('转化失败');
            }
        }
    }

    /**
     * @Apidoc\Title("转化记录")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/zh_list")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     */
    public function change_list()
    {
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        $with = new Change();
        $where[] = ['user_id', '=', $this->user_id];
        $data = [];
        $lists = $with->where($where)
            ->order('add_time desc,id desc')
            ->page($pi, $ps)
            ->withoutField('id,user_id')
            ->select()->each(function ($item) {
                return $item;
            });
        $data['watchlist'] = $lists;
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("申请提现")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/Withdrawals")
     * @Apidoc\Param("step",type="int",require=true,default="1",desc="当前步数")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Param("money",type="int",require=true,default="1",desc="提现金额")
     * @Apidoc\Param("tx_type",type="int",require=true,default="",desc="提现方式")
     * @Apidoc\Param("code",type="string",default="",desc="验证码")
     */
    public function withdrawals()
    {
        $step = input('step');
        if (empty($step) || !in_array($step, [1, 2])) {
            throw new MyException('提交参数有误');
        }
        $user_with_sms_enable = getSysConfig('sms.user_with_sms_enable');
        $sms_time_out = getSysConfig('sms.sms_time_out');//过期时间
        //提现开关
        $cash_open = getSysConfig('cash.cash_open');
        //判断是否绑定了微信和支付宝 至少绑定一个
        $is_wx_bind = $is_zfb_bind = 0;
        //判断是否绑定了微信
        $third_find = ThirdUser::where("uid=$this->user_id and type=2")->find();
        if ($third_find) {
            $is_wx_bind = 1;
        }
        //判断是否绑定了支付宝
        if ($this->user['zhifubao'] && $this->user['realname']) {
            $is_zfb_bind = 1;
        }
        if ($is_wx_bind == 0 && $is_zfb_bind == 0) {
            throw new MyException('请先设置提现账户', 50);
        }
        if ($is_wx_bind == 1 && $is_zfb_bind == 1) {
            $temp_tx_type = 1;
        } elseif ($is_wx_bind) {
            $temp_tx_type = 1;
        } else {
            $temp_tx_type = 2;
        }
        if ($step == 1) {
            $return_data['user_with_sms_enable'] = $user_with_sms_enable;
            $return_data['sms_time_out'] = $sms_time_out;
            $return_data['mobile'] = $this->user['mobile'];
            $return_data['user_money'] = $this->user['user_money'];
            $return_data['cash_open'] = $cash_open;
            $return_data['is_wx_bind'] = $is_wx_bind;
            $return_data['is_zfb_bind'] = $is_zfb_bind;
            $return_data['temp_tx_type'] = $temp_tx_type;
            throw new MyException('获取成功', 10, $return_data);
        } else {
            if ($cash_open != 1) {
                throw new MyException('提现暂未开放');
            }
            $user = get_user_info($this->user_id);
            if ($user['is_lock'] == 1) {
                throw new MyException('用户状态异常');
            }
            $money = input('money');
            $tx_type = input('tx_type');
            $code = input('code');
            if (!in_array($tx_type, [1, 2])) {
                throw new MyException('提交参数有误');
            }
            if ($tx_type == 1 && $is_wx_bind == 0) {
                throw new MyException('非法提交');
            }
            if ($tx_type == 2 && $is_zfb_bind == 0) {
                throw new MyException('非法提交');
            }
            if ($money == '' || !is_numeric($money) || $money <= 0) {
                throw new MyException('请输入正确的提现金额');
            }
            $bj_tx_min = getSysConfig('cash.ye_tx_min');//最少提现
            $ye_tx_xishu = getSysConfig('cash.ye_tx_xishu');//提现系数
            $bj_tx_num = getSysConfig('cash.ye_tx_num');//余额每日可提现次数
            if ($bj_tx_num > 0) {
                $count_where[] = ['user_id', '=', $this->user_id];
                $count_where[] = ['type', '=', 1];
                $count = Db::name('withdrawals')
                    ->where($count_where)
                    ->whereDay('create_time')
                    ->count();
                if ($count >= $bj_tx_num) {
                    $msg = sprintf('粮票每日可提现%s次', $bj_tx_num);
                    throw new MyException($msg);
                }
            }
            if ($money > $user['user_money']) {
                $msg = sprintf('粮票不足,可用%s元!', $user['user_money']);
                throw new MyException($msg);
            }
            if ($ye_tx_xishu > 0) {
                if (($money * 100000) % ($ye_tx_xishu * 100000) != 0) {
                    $msg = sprintf('粮票提现为%s元的整数倍', $ye_tx_xishu);
                    throw new MyException($msg);
                }
            }
            if ($bj_tx_min > 0) {
                if ($money < $bj_tx_min) {
                    $msg = sprintf('粮票最少提现%s元起!', $bj_tx_min);
                    throw new MyException($msg);
                }
            }
            if ($user_with_sms_enable) {
                $check = yz_sms_code($this->user['mobile'], $code);
                if ($check['code'] != 200) {
                    throw new MyException($check['msg']);
                }
            }
            $bj_tx_sxf = getSysConfig('cash.ye_tx_sxf');//提现手续费
            $insert['order_sn'] = getOrderSn('withdrawals', 'w');
            $insert['user_id'] = $this->user_id;
            $insert['tx_type'] = $tx_type;
            $insert['money'] = $money;
            $insert['taxfee'] = $money * ($bj_tx_sxf / 100);
            $insert['true_money'] = $money - $insert['taxfee'];
            $insert['zhifubao'] = $user['zhifubao'];
            $insert['realname'] = $user['realname'];
            Withdrawals::create($insert);
            $log = accountLog($user['user_id'], -$money, '申请提现');
            if ($log) {
                throw new MyException('已提交申请', 200);
            } else {
                throw new MyException('提交失败');
            }
        }
    }

    /**
     * @Apidoc\Title("提现记录")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_tx_list")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Param("status",type="string",require=true,default="",desc="审核状态")
     */
    public function with_list()
    {
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        $status = input('status');
        $with = new Withdrawals();
        $where[] = ['user_id', '=', $this->user_id];
        if ($status) {
            if ($status == '1') {
                $where[] = ['status', '=', -1];
            } else {
                $where[] = ['status', '=', $status - 1];
            }
        }
        $data = [];
        $list = $with->where($where)
            ->order('create_time desc,id desc')
            ->page($pi, $ps)
            ->field('id,tx_type,money,taxfee,true_money,zhifubao,realname,status,create_time,check_time,refuse_time')
            ->select()->each(function ($item) {
                $item['status_text'] = $item['status_text'];
                return $item;
            });
        $data['list'] = $list;
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("金币充值")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/Recharge")
     * @Apidoc\Header(ref="auth")
     * @Apidoc\Param("step",type="int",require=true,default="1",desc="当前步数")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Param("type",type="int",require=true,default="",desc="充值方式2微信")
     * @Apidoc\Param("openid",type="string",default="",desc="openid")
     * @Apidoc\Param("money",type="int",require=true,default="",desc="充值金额")
     */
    public function recharge()
    {
        $step = input('step');
        if (empty($step) || !in_array($step, [1, 2])) {
            throw new MyException('提交参数有误');
        }
        $recharge = getSysConfig('recharge');
        if ($step == 1) {
            $result = $recharge;
            $return_data['jinbi'] = $this->user['jinbi'];
            $return_data['result'] = $result;
            throw new MyException('获取成功', 10, $return_data);
        } else {
            $type = input('type');
            $openid = input('openid');
            if ($recharge['cz_open'] == 0) {
                throw new MyException('充值暂未开放', 50);
            }
            if (!in_array($type, [1, 2, 3])) {
                throw new MyException('充值方式有误');
            }
            $money = input('money');
            if ($money == '' || !is_numeric($money) || $money <= 0) {
                throw new MyException('请输入正确的充值金额');
            }
            if (empty($openid)) {
                throw new MyException('提交参数有误');
            }
            if ($recharge['cz_min'] > 0) {
                if ($money < $recharge['cz_min']) {
                    throw new MyException("最少充值金额为{$recharge['cz_min']}元");
                }
            }
            if ($recharge['cz_xishu'] > 0) {
                if (($money * 100000) % ($recharge['cz_xishu'] * 100000) != 0) {
                    throw new MyException("充值金额为{$recharge['cz_xishu']}元的整数倍");
                }
            }
            $insert['order_sn'] = getOrderSn('recharge', 'r');
            $insert['type'] = $type;
            $insert['user_id'] = $this->user_id;
            $insert['order_amount'] = $money;
            $log = Recharge::create($insert);
            if ($log) {
                $wxpay = new WxPayXcx($this->app);
                $result = $wxpay->createWxData($insert['order_sn'], $money, $openid);
                if ($result['code'] == 1) {
                    throw new MyException("获取成功", 20, ['result' => $result['data']]);
                } else {
                    throw new MyException("获取支付失败");
                }
            } else {
                throw new MyException('充值订单创建失败');
            }
        }
    }

    /**
     * @Apidoc\Title("充值记录")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/cz_list")
     * @Apidoc\Header(ref="auth")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Param("status",type="string",require=true,default="",desc="审核状态")
     */
    public function RechargeList()
    {
        $pi = input('pageIndex');
        $ps = input('pageSize');
        $status = input('status');
        $with = new Recharge();
        $where[] = ['user_id', '=', $this->user_id];
        if ($status) {
            if ($status == '1') {
                $where[] = ['order_status', '=', -1];
            } else {
                $where[] = ['order_status', '=', $status - 1];
            }
        }
        $data = [];
        $lists = $with->where($where)
            ->order('add_time desc,id desc')
            ->page($pi, $ps)
            ->field('id,order_sn,type,order_amount,add_time,order_status')
            ->select()->each(function ($item) {
                $item['status_text'] = $item['status_text'];
                $item['type_text'] = $item['type_text'];
                return $item;
            });
        $data['list'] = $lists;
        throw new MyException("获取成功", 200, $data);
    }

    /**
     * @Apidoc\Title("充值取消或支付")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/do_cz_list")
     * @Apidoc\Header(ref="auth")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("type",type="int",require=true,default="",desc="操作类型1取消2支付")
     * @Apidoc\Param("id",type="int",require=true,default="",desc="充值id")
     * @Apidoc\Param("openid",type="string",default="",desc="openid")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     */
    public function DoRechargeList()
    {
        $id = input('id/d', 0);
        $order = Recharge::where(['user_id' => $this->user_id, 'id' => $id])->find();
        if (empty($order)) {
            throw new MyException('充值不存在');
        }
        $type = input('type', 0);
        if (!in_array($type, [1, 2])) {
            throw new MyException('提交参数有误');
        }
        if ($order['order_status'] != -1) {
            throw new MyException('充值不存在');
        }
        if ($type == 1) {
            $order->order_status = 2;
            $order->cancel_time = time();
            $res = $order->save();
            if ($res) {
                throw new MyException('操作成功', 200);
            } else {
                throw new MyException('操作失败');
            }
        } else {
            $openid = input('openid');
            if (empty($openid)) {
                throw new MyException('提交参数有误');
            }
            $wxpay = new WxPayXcx($this->app);
            $result = $wxpay->createWxData($order['order_sn'], $order['order_amount'], $openid);
            if ($result['code'] == 1) {
                throw new MyException("获取成功", 50, ['result' => $result['data']]);
            } else {
                throw new MyException("获取支付失败");
            }
        }
    }

    /**
     * @Apidoc\Title("资金明细")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_points_list")
     * @Apidoc\Header(ref="auth")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("type",type="int",default="0",desc="1粮票2积分3牧场补贴4储备金")
     */
    public function get_points()
    {
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        $type = input('type', 0);
        $where['user_id'] = $this->user_id;
        if ($type) {
            $where['type'] = $type;
        }
        $account_log = new AccountLog();
        $lists = $account_log
            ->where($where)
            ->order('log_id desc')
            ->page($pi, $ps)
            ->field('money,add_time,desc')
            ->select()->toArray();
        throw new MyException('获取成功', 200, ['list' => $lists]);
    }

    /**
     * @Apidoc\Title("钱包列表")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_my_wallet_list")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("type",type="int",default="0",desc="0已拥有1待领取")
     */
    public function get_user_qianbao_list()
    {
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        $type = input('type', 0);
        if ($type) {
            //查询认养订单
            $where = "user_id=$this->user_id and order_status>0 and surplus_yield>0 and feed_status in (2,3)";
            $lists = FosterOrder::where($where)
                ->field("order_id,wid,((day_sy*goods_num)+speed) as money,feed_status,add_time")
                ->page($pi, $ps)
                ->order('feed_status asc,order_id desc')
                ->select()->each(function ($item) {
                    $item['name'] = $item['qianbao']['name'];
                    unset($item['qianbao']);
                    return $item;
                });
        } else {
            $where['user_id'] = $this->user_id;
            $account_log = new UserWallet();
            $lists = $account_log
                ->where($where)
                ->order('id desc')
                ->page($pi, $ps)
                ->field('id,wid,money,add_time')
                ->select()->each(function ($item) {
                    $item['name'] = $item['qianbao']['name'];
                    unset($item['qianbao']);
                    return $item;
                });
        }
        throw new MyException('获取成功', 200, ['list' => $lists]);
    }

    /**
     * @Apidoc\Title("认养订单待领取列表")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_my_wallet_dlq_list")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     */
    public function get_user_qianbao_dlq_list()
    {
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        //查询待领取订单
        $where = "user_id=$this->user_id and order_status=1";
        $lists = FosterOrder::where($where)
            ->field("wid,sum(surplus_yield) as money")
            ->page($pi, $ps)
            ->group('wid')
            ->order('order_id desc')
            ->select()->each(function ($item) {
                $item['name'] = $item['qianbao']['name'];
                unset($item['qianbao']);
                return $item;
            });
        throw new MyException('获取成功', 200, ['list' => $lists]);
    }

    /**
     * @Apidoc\Title("某票明细")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_my_wallet_log")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("u_wid",type="int",default="",desc="user_wallet表id")
     */
    public function get_user_qianbao_log()
    {
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        $u_wid = input('u_wid', 0);
        $where['user_id'] = $this->user_id;
        if ($u_wid) {
            $where['u_wid'] = $u_wid;
        }
        $account_log = new UserWalletLog();
        $lists = $account_log
            ->where($where)
            ->order('id desc')
            ->page($pi, $ps)
            ->field('money,desc,add_time')
            ->select()->each(function ($item) {
                $item['time_text'] = date('Y-m-d', $item->getData('add_time'));
                unset($item['add_time']);
                return $item;
            });
        throw new MyException('获取成功', 200, ['list' => $lists]);
    }

    /**
     * @Apidoc\Title("钱包出售")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/my_wallet_sell")
     * @Apidoc\Param("step",type="int",require=true,default="1",desc="当前步数")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("id",type="int",require=true,default="",desc="表id")
     * @Apidoc\Param("money",type="float",require=true,default="",desc="交易金额")
     * @Apidoc\Param("paypwd",type="string",require=true,default="",desc="交易密码")
     */
    public function user_wallet_sell()
    {
        $step = input('step');
        if (empty($step) || !in_array($step, [1, 2])) {
            throw new MyException('提交参数有误');
        }
        $id = input('id');
        if (empty($id)) {
            throw new MyException('提交参数有误');
        }
        //判断是否完善了交易密码
        if (empty($this->user['paypwd'])) {
            throw new MyException('请先设置交易密码', 50);
        }
        $qianbao = UserWallet::where("id={$id} and user_id=$this->user_id")->find();
        if (empty($qianbao)) {
            throw new MyException('钱包不存在');
        }
        $wallet = $qianbao['qianbao'];
        $name = $wallet['name'];
        $jy_min = $wallet['jy_min'];
        $jy_sxf = $wallet['jy_sxf'];
        $jy_price = $wallet['jy_price'];
        if ($step == 1) {
            $return_data['name'] = $wallet['name'];
            $return_data['user_money'] = $qianbao['money'];
            $return_data['jy_min'] = $jy_min;
            $return_data['jy_sxf'] = $jy_sxf;
            $return_data['jy_price'] = $jy_price;
            throw new MyException('获取成功', 10, $return_data);
        } else {
            $user_money = UserWallet::where('id', $id)->value('money');
            $money = input('money');
            $paypwd = input('paypwd');
            if ($money == '' || !is_numeric($money) || $money <= 0) {
                throw new MyException('请输入正确的交易金额');
            }
            if ($jy_min > 0) {
                if ($money < $jy_min) {
                    $msg = sprintf('最小交易金额为%s元!', $jy_min);
                    throw new MyException($msg);
                }
            }
            $amount = $money * $jy_price;
            $taxfee = $amount * ($jy_sxf / 100);
            if ($money > $user_money) {
                $msg = sprintf('%s不足,可用%s元!', $name, $user_money);
                throw new MyException($msg);
            }
            if (empty($paypwd)) {
                throw new MyException('请输入交易密码');
            }
            if (encrypt($paypwd) != $this->user['paypwd']) {
                throw new MyException('交易密码不正确');
            }
            $log = user_wallet_log($this->user_id, $id, -$money, "会员交易");
            $log1 = true;
            if ($log) {
                $user_wallet = UserWallet::where("id={$id}")->find();
                if ($user_wallet['money'] >= 0) {
                    $insert['user_id'] = $this->user_id;
                    $insert['wid'] = $user_wallet['wid'];
                    $insert['money'] = $money;
                    $insert['jy_sxf'] = $taxfee;
                    $insert['jy_price'] = $jy_price;
                    $insert['amount'] = $amount;
                    $log1 = UserWalletDeal::create($insert);
                }
            }
            if ($log && $log1) {
                throw new MyException('提交成功', 200);
            } else {
                throw new MyException('提交失败');
            }
        }
    }

    /**
     * @Apidoc\Title("钱包转让")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/my_wallet_given")
     * @Apidoc\Param("step",type="int",require=true,default="1",desc="当前步数")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("id",type="int",require=true,default="",desc="表id")
     * @Apidoc\Param("money",type="float",require=true,default="",desc="交易金额")
     * @Apidoc\Param("paypwd",type="string",require=true,default="",desc="交易密码")
     */
    public function user_wallet_given()
    {
        $step = input('step');
        if (empty($step) || !in_array($step, [1, 2])) {
            throw new MyException('提交参数有误');
        }
        $id = input('id');
        if (empty($id)) {
            throw new MyException('提交参数有误');
        }
        //判断是否完善了交易密码
        if (empty($this->user['paypwd'])) {
            throw new MyException('请先设置交易密码', 50);
        }
        $qianbao = UserWallet::where("id={$id} and user_id=$this->user_id")->find();
        if (empty($qianbao)) {
            throw new MyException('钱包不存在');
        }
        $wallet = $qianbao['qianbao'];
        $name = $wallet['name'];
        $g_min = $wallet['g_min'];
        $g_max = $wallet['g_max'];
        $g_xishu = $wallet['g_xishu'];
        $g_sxf = $wallet['g_sxf'];
        if ($step == 1) {
            $return_data['name'] = $wallet['name'];
            $return_data['user_money'] = $qianbao['money'];
            $return_data['g_min'] = $g_min;
            $return_data['g_max'] = $g_max;
            $return_data['g_xishu'] = $g_xishu;
            $return_data['g_sxf'] = $g_sxf;
            throw new MyException('获取成功', 10, $return_data);
        } else {
            $user_money = UserWallet::where('id', $id)->value('money');
            $money = input('money');
            $dfmobile = input('dfmobile');
            $uid = input('uid/d');
            $paypwd = input('paypwd');
            if ($money == '' || !is_numeric($money) || $money <= 0) {
                throw new MyException('请输入正确的转让金额');
            }
            if (empty($dfmobile)) {
                throw new MyException('请输入对方账号');
            }
            if (empty($uid)) {
                throw new MyException('请输入对方ID');
            }
            $user_where['mobile'] = $dfmobile;
            $user_where['user_id'] = $uid;
            $dfuser = Users::where($user_where)->find();
            if (empty($dfuser) || $dfuser['is_lock'] == 1) {
                throw new MyException('会员不存在或状态异常');
            }
            if ($dfuser['user_id'] == $this->user_id) {
                throw new MyException('转让方式不允许');
            }
            if ($g_min > 0) {
                if ($money < $g_min) {
                    $msg = sprintf('最小转让金额为%s元!', $g_min);
                    throw new MyException($msg);
                }
            }
            if ($g_max > 0) {
                if ($money > $g_max) {
                    $msg = sprintf('最大转让金额为%s元!', $g_max);
                    throw new MyException($msg);
                }
            }
            if ($g_xishu > 0) {
                if (($money * 100000) % ($g_xishu * 100000) != 0) {
                    $msg = sprintf('转让金额为%s元的整数倍!', $g_xishu);
                    throw new MyException($msg);
                }
            }
            $taxfee = $money * ($g_sxf / 100);
            $amount = $money + $taxfee;
            if ($amount > $user_money) {
                $msg = sprintf('%s不足,可用%s元!', $name, $user_money);
                throw new MyException($msg);
            }
            if (empty($paypwd)) {
                throw new MyException('请输入交易密码');
            }
            if (encrypt($paypwd) != $this->user['paypwd']) {
                throw new MyException('交易密码不正确');
            }
            $log = user_wallet_log($this->user_id, $id, -$amount, "会员转让");
            $log1 = $log2 = true;
            if ($log) {
                $user_wallet = UserWallet::where("id={$id}")->find();
                if ($user_wallet['money'] >= 0) {
                    $insert['user_id'] = $this->user_id;
                    $insert['d_user_id'] = $dfuser['user_id'];
                    $insert['u_wid'] = $user_wallet['id'];
                    $insert['wid'] = $user_wallet['wid'];
                    $insert['money'] = $money;
                    $insert['taxfee'] = $taxfee;
                    $insert['amount'] = $amount;
                    $log1 = UserWalletGiven::create($insert);
                    $log2 = user_wallet_log($dfuser['user_id'], 0, $money, "会员转让", $this->user_id, $user_wallet['wid']);
                }
            }
            if ($log && $log1 && $log2) {
                throw new MyException('转让成功', 200);
            } else {
                throw new MyException('转让失败');
            }
        }
    }

    /**
     * @Apidoc\Title("钱包转让明细")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_my_wallet_given_log")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("u_wid",type="int",default="",desc="user_wallet表id")
     */
    public function get_user_wallet_given_log()
    {
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        $u_wid = input('u_wid', 0);
        $where['user_id'] = $this->user_id;
        if ($u_wid) {
            $where['u_wid'] = $u_wid;
        }
        $account_log = new UserWalletGiven();
        $lists = $account_log
            ->where($where)
            ->order('id desc')
            ->page($pi, $ps)
            ->field('d_user_id,money,taxfee,amount,add_time')
            ->select()->each(function ($item) {
                $item['sub_mobile'] = substr_replace($item['duser']['mobile'], '****', 3, 4);
                unset($item['duser']);
                return $item;
            });
        throw new MyException('获取成功', 200, ['list' => $lists]);
    }

    /**
     * @Apidoc\Title("交易大厅")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_jy_list")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     */
    public function user_wallet_deal_list()
    {
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        $where = [];
        $where[] = ['status', '=', -1];
        $where[] = ['user_id', '<>', $this->user_id];
        $account_log = new UserWalletDeal();
        $lists = $account_log
            ->where($where)
            ->order('id desc')
            ->page($pi, $ps)
            ->field('id,user_id,wid,money,amount')
            ->select()->each(function ($item) {
                $item['head_pic'] = $item['user']['head_pic'];
                $item['mobile'] = $item['user']['mobile'];
                $item['name'] = $item['qianbao']['name'];
                unset($item['qianbao'], $item['user']);
                return $item;
            });
        throw new MyException('获取成功', 200, ['list' => $lists]);
    }

    /**
     * @Apidoc\Title("交易购买")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/jy_buy")
     * @Apidoc\Param("step",type="int",require=true,default="",desc="当前步数")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Param("id",type="int",default="",desc="交易表id")
     * @Apidoc\Param("pay_code",type="string",default="",desc="支付方式")
     */
    public function user_wallet_buy()
    {
        $step = input('step', 0);
        if (!in_array($step, [1, 2])) {
            throw new MyException('提交参数有误', 100);
        }
        $id = input('id');
        if (empty($id)) {
            throw new MyException('提交参数有误', 100);
        }
        $userWalletModel = new UserWalletDeal();
        $where = "user_id!=$this->user_id and id={$id} and status=-1";
        $detail = $userWalletModel->where($where)->find();
        if (empty($detail)) {
            throw new MyException('交易不存在', 100);
        }
        $detail['head_pic'] = $detail['user']['head_pic'];
        $detail['mobile'] = $detail['user']['mobile'];
        $detail['name'] = $detail['qianbao']['name'];
        unset($detail['qianbao'], $detail['user']);
        $pay_list = [
            //            [
            //                'code' => 'weixin',
            //                'name' => '微信支付',
            //            ],
            //            [
            //                'code' => 'zfb',
            //                'name' => '支付宝支付',
            //            ],
            [
                'code' => 'money',
                'name' => '粮票支付(' . $this->user['user_money'] . ')',
            ],
            [
                'code' => 'mcbt',
                'name' => '牧场补贴支付(' . $this->user['mcbt'] . ')',
            ]
        ];
        $arr = [];
        foreach ($pay_list as $pay) {
            $arr[] = $pay['code'];
        }
        if ($step == 1) {
            $data['detail'] = $detail;
            $data['pay_list'] = $pay_list;
            throw new MyException('获取成功', 10, $data);
        } else {
            $pay_code = input('pay_code');
            $openid = input('openid');
            if (!in_array($pay_code, $arr)) {
                throw new MyException('支付方式有误', 20);
            }
            $order_amount = $detail['amount'];
            switch ($pay_code) {
                case 'money':
                    if ($this->user['user_money'] < $order_amount) {
                        $str = sprintf('粮票不足,可用%s!', $this->user['user_money']);
                        throw new MyException($str, 50);
                    }
                    $detail_update['pay_name'] = '粮票';
                    break;
                case 'mcbt':
                    if ($this->user['mcbt'] < $order_amount) {
                        $str = sprintf('牧场补贴不足,可用%s!', $this->user['mcbt']);
                        throw new MyException($str, 50);
                    }
                    $detail_update['pay_name'] = '牧场补贴';
                    break;
                case 'weixin':
                    $detail_update['pay_name'] = '微信支付';
                    throw new MyException('微信支付暂未开放', 50);
                    break;
                default:
                    $detail_update['pay_name'] = '支付宝支付';
                    throw new MyException('支付宝支付暂未开放', 50);
                    break;
            }
            $detail_update['pay_code'] = $pay_code;
            $detail_update['d_user_id'] = $this->user_id;
            $detail_update['status'] = 1;
            $detail_update['end_time'] = time();
            $res = $detail->save($detail_update);
            switch ($pay_code) {
                case 'money':
                    $log = accountLog($this->user_id, -$order_amount, '交易扣除');
                    $text = 'user_money';
                    break;
                case 'mcbt':
                    $log = accountLog($this->user_id, -$order_amount, '交易扣除', 3);
                    $text = 'mcbt';
                    break;
                default:
                    throw new MyException('其它支付方式暂未开放', 50);
                    break;
            }
            if ($res && $log) {
                $user_money = Users::where('user_id', $this->user_id)->value($text);
                if ($user_money >= 0) {
                    //给卖家粮票 要减去手续费
                    $order_amount1 = $order_amount - $detail['jy_sxf'];
                    $desc = sprintf('出售%s收入', $detail['qianbao']['name']);
                    $log1 = accountLog($detail['user_id'], $order_amount1, $desc);
                    //给买家增加某票
                    $log2 = user_wallet_log($this->user_id, 0, $detail['money'], "交易买入", 0, $detail['wid']);
                    if ($log1 && $log2) {
                        throw new MyException("交易成功", 200);
                    } else {
                        throw new MyException("交易失败");
                    }
                } else {
                    throw new MyException("交易失败");
                }
            } else {
                throw new MyException("交易失败");
            }
        }
    }

    /**
     * @Apidoc\Title("会员交易列表")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_user_jy_list")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("type",type="int",require=true,default="",desc="类型1出售2买入")
     * @Apidoc\Param("status",type="int",require=true,default="",desc="状态-1交易中1完成2系统回收3取消 当type=1时传入")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     */
    public function get_user_wallet_deal_list()
    {
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        $type = input('type');
        $status = input('status');
        $where = [];
        if ($type == 1) {
            $where[] = ['user_id', '=', $this->user_id];
            if ($status) {
                switch ($status) {
                    case 1://出售中
                        $where[] = ['status', '=', -1];
                        break;
                    case 2://已完成
                        $where[] = ['status', 'in', "1,2"];
                        break;
                    case 3://已取消
                        $where[] = ['status', '=', 3];
                        break;
                }
            }
        } else {
            $where[] = ['d_user_id', '=', $this->user_id];
        }
        $account_log = new UserWalletDeal();
        $lists = $account_log
            ->where($where)
            ->order('id desc')
            ->page($pi, $ps)
            ->field("id,user_id,wid,money,amount,jy_sxf,end_time,status,add_time")
            ->select()->each(function ($item) {
                $item['total_amount'] = $item['amount'] - $item['jy_sxf'];
                $item['status_text'] = $item['status_text'];
                $item['time_text'] = date('Y-m-d', $item->getData('add_time'));
                $item['mobile'] = $item['user']['mobile'];
                $item['name'] = $item['qianbao']['name'];
                unset($item['qianbao'], $item['user']);
                return $item;
            });
        throw new MyException('获取成功', 200, ['list' => $lists]);
    }

    /**
     * @Apidoc\Title("交易详情")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/user_jy_xq")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Param("id",type="int",default="",desc="交易表id")
     */
    public function user_wallet_deal_detail()
    {
        $id = input('id');
        if (empty($id)) {
            throw new MyException('提交参数有误', 100);
        }
        $userWalletModel = new UserWalletDeal();
        $where = "user_id=$this->user_id and id={$id}";
        $detail = $userWalletModel->where($where)->find();
        if (empty($detail)) {
            throw new MyException('交易不存在', 100);
        }
        $detail['name'] = $detail['qianbao']['name'];
        $detail['status_text'] = $detail['status_text'];
        $detail['time_text'] = date('Y-m-d', $detail->getData('add_time'));
        unset($detail['qianbao'], $detail['user']);
        $data['detail'] = $detail;
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("取消交易")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/user_jy_qx")
     * @Apidoc\Param("user_id",type="int",require=true,default="1",desc="用户id")
     * @Apidoc\Param("id",type="int",require=true,default="1",desc="交易id")
     */
    public function user_wallet_deal_cancel()
    {
        $id = input('id/d', 0);
        $user_wallet_model = new UserWalletDeal();
        $user_wallet = $user_wallet_model->where(['user_id' => $this->user_id, 'id' => $id])->find();
        if (empty($user_wallet)) {
            throw new MyException('交易不存在');
        }
        if ($user_wallet['status'] != -1) {
            throw new MyException('交易状态不允许取消');
        }
        $user_wallet_update['status'] = 3;
        $user_wallet_update['end_time'] = time();
        $row = $user_wallet->save($user_wallet_update);
        $log = user_wallet_log($this->user_id, 0, $user_wallet['money'], '交易取消退回', 0, $user_wallet['wid']);
        if ($row && $log) {
            throw new MyException('操作成功', 200);
        } else {
            throw new MyException('操作失败');
        }
    }

    /**
     * @Apidoc\Title("某票列表")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/get_piao_list")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("is_all",type="int",require=true,default="",desc="是否查询全部")
     */
    public function get_wallet_list()
    {
        $is_all = input('is_all', 0);
        $where = [];
        $wallet_model = new Wallet();
        if ($is_all) {
            $list = $wallet_model
                ->where($where)
                ->order('id desc')
                ->field('id,name')
                ->select()->each(function ($item) {
                    return $item;
                });
        } else {
            $pi = input('pageIndex', 1);
            $ps = input('pageSize', 20);
            $list = $wallet_model
                ->where($where)
                ->order('id desc')
                ->page($pi, $ps)
                ->field('id,name')
                ->select()->each(function ($item) {
                    return $item;
                });
        }
        throw new MyException('获取成功', 200, ['list' => $list]);
    }

    /**
     * @Apidoc\Title("团队分红领取记录")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/td_fh_lq_list")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("type",type="int",require=true,default="1",desc="类型1团队分红2加权分红")
     */
    public function get_td_fh_lq_list()
    {
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        $type = input('type', 1);
        $where['user_id'] = $this->user_id;
        if (in_array($type, [1, 2])) {
            $where['type'] = $type;
        } else {
            $where['type'] = 1;
        }
        $account_log = new JlLqLog();
        $lists = $account_log
            ->where($where)
            ->order('id desc')
            ->page($pi, $ps)
            ->field('money,desc,add_time')
            ->select()->each(function ($item) {
                return $item;
            });
        $data['list'] = $lists;
        throw new MyException('获取成功', 200, $data);
    }

    /**
     * @Apidoc\Title("团队分红领取")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/td_fh_lq")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     */
    public function td_fh_lq()
    {
        $jl_log_model = new JlLog();
        $td_fh_dlq = $jl_log_model->where("user_id=$this->user_id and status=1")->sum("money");
        if ($td_fh_dlq <= 0) {
            throw new MyException('没有奖励可以领取');
        }
        $insert['user_id'] = $this->user_id;
        $insert['money'] = $td_fh_dlq;
        $insert['desc'] = '团队分红';
        $log = JlLqLog::create($insert);
        $log1 = accountLog($this->user_id, $td_fh_dlq, '团队分红', 1, 0, 0, '', $td_fh_dlq);
        if ($log && $log1) {
            $jl_log_update['jid'] = $log->id;
            $jl_log_update['status'] = 2;
            $jl_log_update['end_time'] = time();
            $jl_log_model->where("user_id=$this->user_id and status=1")->save($jl_log_update);
            throw new MyException('领取成功', 200);
        } else {
            throw new MyException('领取失败');
        }
    }

    /**
     * @Apidoc\Title("团队分红奖励记录")
     * @Apidoc\Method("POST")
     * @Apidoc\url("api/td_fh_log_list")
     * @Apidoc\Param(ref="pagingParam")
     * @Apidoc\Param("user_id",type="int",require=true,default="",desc="用户id")
     * @Apidoc\Param("status",type="int",require=true,default="",desc="状态-1待发放1待领取2已领取")
     */
    public function get_td_fh_log_list()
    {
        $pi = input('pageIndex', 1);
        $ps = input('pageSize', 20);
        $status = input('status');
        $where['user_id'] = $this->user_id;
        if ($status) {
            $where['status'] = $status;
        }
        $account_log = new JlLog();
        $lists = $account_log
            ->where($where)
            ->order('id desc')
            ->page($pi, $ps)
            ->field('level,amount,jl_bili,money,desc,add_time')
            ->select()->each(function ($item) {
                return $item;
            });
        $data['list'] = $lists;
        throw new MyException('获取成功', 200, $data);
    }

    public function loginByPhone(PlatFormFactory $platFormFactory)
    {
        Db::startTrans();
        try {
            $platformObj = $platFormFactory->create();

            $user = $platformObj->loginByPhone();
            Db::commit();
        } catch (\Throwable $throwable) {
            throw new MyException($throwable->getMessage(), 400);
        }

        throw new MyException('登录成功', 200, $user);
    }
}
